package com.morgankelly.dao;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.morgankelly.po.Account;
import com.morgankelly.po.Blog;
import com.morgankelly.po.BlogComment;
import com.morgankelly.util.Constants;
import com.morgankelly.util.PMF;

public class BlogCommentDAO extends GenericDAO<BlogComment> {
	
	private static BlogCommentDAO instance = null;

	private BlogCommentDAO() {}

	public static synchronized BlogCommentDAO get() {
		if (instance == null) {instance = new BlogCommentDAO();}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public int getCommentNumByBlogID(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Key keyObj = KeyFactory.createKey(Blog.class.getSimpleName(), id);

		Query query = pm.newQuery(BlogComment.class, "blogKey == keyObj");
		query.declareParameters("com.google.appengine.api.datastore.Key keyObj");

		List<BlogComment> blogCommentList = (List<BlogComment>) query.execute(keyObj);

		return  blogCommentList.size();
	}
	
	public void add(BlogComment blogComment) {

		Key accountKey = KeyFactory.createKey(Account.class.getSimpleName(), blogComment.getAccountID());
		Key blogKey = KeyFactory.createKey(Blog.class.getSimpleName(), blogComment.getBlogID());

		Calendar current = Calendar.getInstance();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.FORMAT_TIME_5);

		blogComment.setCreateTime(simpleDateFormat.format(current.getTime()));
		blogComment.setAccountKey(accountKey);
		blogComment.setBlogKey(blogKey);
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistent(blogComment);
	}

}